package com.vdg.lockapp;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.vdg.data.SettingData;
import com.vdg.lockapp.service.LockService;
import com.vdg.lockapp.service.LockService.LocalBinder;
import com.vdg.ui.view.TextViewPlus;
import com.vdg.util.ImageLoader;
import com.vdg.util.Utilities;

public class PassCodeActivity extends Activity {
	private TextView mBtnOk;
	private LockService mService;
	private final String TAG = "PassCodeActivity";
	private EditText mEdtPassCode;
	private TextViewPlus mTxvTitle;
	private TextViewPlus mTxvHint;
	private Intent mIntent;
	private ImageLoader mImageLoader;
	private ImageView mImvIcon;
	private TextViewPlus mTxvZezo;
	private TextViewPlus mTxvOne;
	private TextViewPlus mTxvTwo;
	private TextViewPlus mTxvThree;
	private TextViewPlus mTxvFour;
	private TextViewPlus mTxvFive;
	private TextViewPlus mTxvSix;
	private TextViewPlus mTxvSeven;
	private TextViewPlus mTxvEight;
	private TextViewPlus mTxvNine;
	private ImageButton mBtnBackSpace;
	private PASS_CODE_ACTION_TYPE mActionType;
	private String mPassword = null;
	private LinearLayout mLnAds;
	private AdView mAdView;
	private ImageButton mBtnBack;
	private String mNewPassword;

	public enum PASS_CODE_ACTION_TYPE {
		UNLOCK_ACTION, CHANGE_PASSWORD_ACTION, SETUP_PASSWORD_ACTION
	}

	public static final String PASS_CODE_ACTION = "pass_code_action";
	private OnTouchListener otl = new OnTouchListener() {
		public boolean onTouch(View v, MotionEvent event) {
			return true; // the listener has consumed the event
		}
	};
	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
		}

		public void onServiceDisconnected(ComponentName name) {
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pass_code_layout1);
		mImageLoader = ImageLoader.getInstance(this);
		binService();
		init();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unbindService(mServiceConnection);
		super.onDestroy();
	}

	private void binService() {
		Intent s2ServiceIntent = new Intent(this, LockService.class);
		bindService(s2ServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
	}

	private void selectToEnd() {
		mEdtPassCode.setSelection(mEdtPassCode.getText().toString().length());
	}

	private void init() {
		mEdtPassCode = (EditText) findViewById(R.id.edt_passcode);
		mTxvTitle = (TextViewPlus) findViewById(R.id.txv_title);
		mLnAds = (LinearLayout) findViewById(R.id.ln_ads1);
		mBtnBack = (ImageButton) findViewById(R.id.bnt_back);
		AdSize testSize = AdSize.createAdSize(AdSize.SMART_BANNER, this);
		Log.v(TAG, "size = " + testSize.getHeightInPixels(this));
		mLnAds.getLayoutParams().height = testSize.getHeightInPixels(this);
		mIntent = getIntent();
		if (mIntent != null) {
			Log.v(TAG,
					"passcode action = "
							+ mIntent.getStringExtra(PASS_CODE_ACTION));
			mActionType = PASS_CODE_ACTION_TYPE.valueOf(mIntent
					.getStringExtra(PASS_CODE_ACTION));
		}
		mBtnBack.setVisibility(View.GONE);
		mBtnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mActionType == PASS_CODE_ACTION_TYPE.SETUP_PASSWORD_ACTION) {
					mTxvHint.setVisibility(View.VISIBLE);
					mTxvTitle.setVisibility(View.VISIBLE);
					mTxvHint.setText(getResources().getString(
							R.string.enter_password));
					mTxvTitle.setText(getResources().getString(
							R.string.setup_a_password));
					mBtnBack.setVisibility(View.GONE);
					mEdtPassCode.setText("");
					mPassword = "";
				}
				if (mActionType == PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION) {
					mTxvHint.setVisibility(View.VISIBLE);
					mTxvTitle.setVisibility(View.VISIBLE);
					mTxvHint.setText(getResources().getString(
							R.string.enter_old_password));
					mTxvTitle.setText(getResources().getString(
							R.string.change_password));
					mBtnBack.setVisibility(View.GONE);
					mEdtPassCode.setText("");
					mPassword = "";
					mNewPassword = null;
				}
			}
		});
		mImvIcon = (ImageView) findViewById(R.id.imv_icon);
		mTxvHint = (TextViewPlus) findViewById(R.id.txv_hint);
		if (mActionType == PASS_CODE_ACTION_TYPE.UNLOCK_ACTION) {
			mTxvHint.setVisibility(View.VISIBLE);
			mTxvTitle.setVisibility(View.GONE);
			String appName = Utilities.getAppName(this,
					mIntent.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME));
			mTxvTitle.setText(getResources().getString(
					R.string.unlock_app_name, appName));
		}
		if (mActionType == PASS_CODE_ACTION_TYPE.SETUP_PASSWORD_ACTION) {
			mTxvHint.setVisibility(View.VISIBLE);
			mTxvTitle.setVisibility(View.VISIBLE);
			mTxvHint.setText(getResources().getString(R.string.enter_password));
			mTxvTitle.setText(getResources().getString(
					R.string.setup_a_password));
		}
		if (mActionType == PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION) {
			mTxvHint.setVisibility(View.VISIBLE);
			mTxvTitle.setVisibility(View.VISIBLE);
			mTxvHint.setText(getResources().getString(
					R.string.enter_old_password));
			mTxvTitle.setText(getResources()
					.getString(R.string.change_password));
		}
		mEdtPassCode.setOnTouchListener(otl);
		final Intent returnIntent = new Intent();
		returnIntent.putExtra(PASS_CODE_ACTION, mActionType.toString());
		// TODO Auto-generated method stub
		final String passcode = SettingData.getInstance(PassCodeActivity.this)
				.getPassCode();
		mEdtPassCode.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (mActionType == PASS_CODE_ACTION_TYPE.UNLOCK_ACTION) {
					if (s.toString().equals(passcode)) {
						setResult(RESULT_OK, returnIntent);
						mService.unlockApp(mIntent
								.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME));
						PassCodeActivity.this.finish();
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		if (mIntent != null) {
			if (mActionType == PASS_CODE_ACTION_TYPE.UNLOCK_ACTION) {
				mImvIcon.setVisibility(View.VISIBLE);
				mImageLoader
						.loadImage(
								mImvIcon,
								Utilities.getAppInformation(
										mIntent.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME),
										PassCodeActivity.this),
								mIntent.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME));
			} else {
				if (mActionType == PASS_CODE_ACTION_TYPE.SETUP_PASSWORD_ACTION) {
					mImvIcon.setImageResource(R.drawable.ic_launcher);
				} else {
					mImvIcon.setVisibility(View.GONE);
				}
			}
		}
		mTxvZezo = (TextViewPlus) findViewById(R.id.txv_zezo);
		mTxvZezo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvZezo.getText().toString());
				selectToEnd();
			}
		});
		mTxvOne = (TextViewPlus) findViewById(R.id.txv_one);
		mTxvOne.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvOne.getText().toString());
				selectToEnd();
			}
		});
		mTxvTwo = (TextViewPlus) findViewById(R.id.txv_two);
		mTxvTwo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvTwo.getText().toString());
				selectToEnd();
			}
		});
		mTxvThree = (TextViewPlus) findViewById(R.id.txv_three);
		mTxvThree.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvThree.getText().toString());
				selectToEnd();
			}
		});
		mTxvFour = (TextViewPlus) findViewById(R.id.txv_four);
		mTxvFour.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvFour.getText().toString());
				selectToEnd();
			}
		});
		mTxvFive = (TextViewPlus) findViewById(R.id.txv_five);
		mTxvFive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvFive.getText().toString());
				selectToEnd();
			}
		});
		mTxvSix = (TextViewPlus) findViewById(R.id.txv_six);
		mTxvSix.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvSix.getText().toString());
				selectToEnd();
			}
		});
		mTxvSeven = (TextViewPlus) findViewById(R.id.txv_seven);
		mTxvSeven.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvSeven.getText().toString());
				selectToEnd();
			}
		});
		mTxvEight = (TextViewPlus) findViewById(R.id.txv_eight);
		mTxvEight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvEight.getText().toString());
				selectToEnd();
			}
		});
		mTxvNine = (TextViewPlus) findViewById(R.id.txv_nine);
		mTxvNine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mEdtPassCode.setText(mEdtPassCode.getText().toString()
						+ mTxvNine.getText().toString());
				selectToEnd();
			}
		});
		mBtnBackSpace = (ImageButton) findViewById(R.id.btn_backspace);
		mBtnBackSpace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mEdtPassCode.getText().toString().length() == 0) {
					return;
				}
				mEdtPassCode
						.setText(mEdtPassCode
								.getText()
								.toString()
								.substring(
										0,
										mEdtPassCode.getText().toString()
												.length() - 1));
				selectToEnd();
			}
		});
		mBtnOk = (TextView) findViewById(R.id.btn_ok);
		mBtnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent returnIntent = new Intent();
				returnIntent.putExtra(PASS_CODE_ACTION, mActionType.toString());
				// TODO Auto-generated method stub
				String passcode = SettingData
						.getInstance(PassCodeActivity.this).getPassCode();
				if (mActionType == PASS_CODE_ACTION_TYPE.UNLOCK_ACTION) {
					if (mEdtPassCode.getText().toString().equals(passcode)) {
						setResult(RESULT_OK, returnIntent);
						mService.unlockApp(mIntent
								.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME));
						PassCodeActivity.this.finish();
					} else {
						mTxvHint.setVisibility(View.VISIBLE);
						mTxvHint.setText(getResources().getString(
								R.string.password_incorrect));
						mEdtPassCode.setText("");
						return;
					}
				} else {
					Log.v(TAG, "pass   = " + mPassword);
					if ((mPassword == null || mPassword.equals(""))
							&& mActionType == PASS_CODE_ACTION_TYPE.SETUP_PASSWORD_ACTION) {
						mPassword = mEdtPassCode.getText().toString();
						mTxvHint.setText(getResources().getString(
								R.string.confirm_your_password));
						mEdtPassCode.setText("");
						mBtnBack.setVisibility(View.VISIBLE);
						Log.v(TAG, "pass111   = " + mPassword);
						return;
					}
					if (mPassword != null
							&& !mPassword.equals("")
							&& mActionType == PASS_CODE_ACTION_TYPE.SETUP_PASSWORD_ACTION) {
						if (mPassword.equals(mEdtPassCode.getText().toString())) {
							SettingData.getInstance(PassCodeActivity.this)
									.setPassCode(mPassword,
											PassCodeActivity.this);
							setResult(RESULT_OK, returnIntent);
							PassCodeActivity.this.finish();
							mPassword = null;
							return;
						} else {
							mTxvHint.setText(getResources().getString(
									R.string.confirm_new_password_incorrect));
							mEdtPassCode.setText("");
							return;
						}
					}
					if ((mPassword == null || mPassword.equals(""))
							&& mActionType == PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION) {
						if (mEdtPassCode.getText().toString().equals(passcode)) {
							mPassword = mEdtPassCode.getText().toString();
							mTxvHint.setText(getResources().getString(
									R.string.enter_new_password));
							mEdtPassCode.setText("");
							mBtnBack.setVisibility(View.VISIBLE);
						} else {
							mTxvHint.setVisibility(View.VISIBLE);
							mTxvHint.setText(getResources().getString(
									R.string.password_incorrect));
							mEdtPassCode.setText("");
							mPassword = "";
						}
						return;
					}
					if (mPassword != null
							&& !mPassword.equals("")
							&& mActionType == PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION
							&& mNewPassword == null) {
						mNewPassword = mEdtPassCode.getText().toString();
						mTxvHint.setText(getResources().getString(
								R.string.confirm_new_password));
						mEdtPassCode.setText("");
						mBtnBack.setVisibility(View.VISIBLE);
					}
					if (mPassword != null
							&& !mPassword.equals("")
							&& mActionType == PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION
							&& mNewPassword != null) {
						if (mNewPassword.equals(mEdtPassCode.getText()
								.toString())) {
							SettingData.getInstance(PassCodeActivity.this)
									.setPassCode(mNewPassword,
											PassCodeActivity.this);
							setResult(RESULT_OK, returnIntent);
							mService.unlockApp(mIntent
									.getStringExtra(LockService.APP_LOCK_PACKAGE_NAME));
							PassCodeActivity.this.finish();
							Toast.makeText(
									mService,
									getResources()
											.getString(
													R.string.change_passcode_sucessfully),
									Toast.LENGTH_LONG).show();
							return;
						} else {
							mTxvHint.setText(getResources().getString(
									R.string.confirm_new_password_incorrect));
							mEdtPassCode.setText("");
							return;
						}
					}
				}
			}
		});
		// AdSize adsize = AdSize.SMART_BANNER;
		// Display display = getWindowManager().getDefaultDisplay();
		// int width = display.getWidth();
		// int height = display.getHeight();
		// int orientation = display.getOrientation();
		// if (width >= 728 && height >= 90) {
		// adsize = AdSize.IAB_LEADERBOARD;
		// Log.v(TAG, "728 x 90");
		// } else if (width >= 468 && height >= 60) {
		// adsize = AdSize.IAB_BANNER;
		// Log.v(TAG, "468 x 60");
		// } else if (width >= 320 && height >= 50) {
		// adsize = AdSize.BANNER;
		// Log.v(TAG, "320 x 50");
		// }
		// Log.v(TAG, "----- " + adsize.getHeight() + "x" + adsize.getWidth());
		// mAdView = new AdView(this, AdSize.SMART_BANNER, getResources()
		// .getString(R.string.ad_mob_id));
		// mLnAds.getLayoutParams().width =
		// AdSize.BANNER.getWidthInPixels(this);
		// mLnAds.addView(mAdView);
		// (new Thread() {
		// public void run() {
		// Looper.prepare();
		// mAdView.loadAd(new AdRequest());
		// }
		// }).start();
		AdView ad = (AdView) findViewById(R.id.adView);
		ad.loadAd(new AdRequest());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_CANCELED);
			if (mActionType != PASS_CODE_ACTION_TYPE.CHANGE_PASSWORD_ACTION) {
				gotoHome();
			}
			PassCodeActivity.this.finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void gotoHome() {
		Intent homeIntent = new Intent(Intent.ACTION_MAIN);
		homeIntent.addCategory(Intent.CATEGORY_HOME);
		homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(homeIntent);
	}
}
